package com.lntea.netty.im.packet.common;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.util.AttributeKey;

import java.util.HashMap;
import java.util.Map;

/**
 * 会话工具类
 */
public class SessionUtil {

    /**
     * userId-channel Map
     */
    private static final Map<String, Channel> userIdChannelMap = new HashMap<>();
    /**
     * channel group Map
     */
    private static final Map<String, ChannelGroup> channelGroupMap = new HashMap<>();

    /**
     * 用户会话绑定连接
     * @param session
     * @param channel
     */
    public static void bindSession(Session session, Channel channel) {
        userIdChannelMap.put(session.getUserId(), channel);
        channel.attr(Attributes.SESSION).set(session);
    }

    /**
     * 用户会话解绑连接
     */
    public static void unbindSession(Channel channel) {
        if (hasLogin(channel)) {
            userIdChannelMap.remove(getSession(channel).getUserId());
            channel.attr(Attributes.SESSION).set(null);
        }
    }

    /**
     * 绑定群组id和ChannelGroup
     * @param groupId
     * @param group
     */
    public static void bindChannelGroup(String groupId, ChannelGroup group) {
        channelGroupMap.put(groupId, group);
    }

    /**
     * 获取ChannelGroup
     * @param groupId
     * @return
     */
    public static ChannelGroup getChannelGroup(String groupId) {
        return channelGroupMap.get(groupId);
    }

    /**
     * 是否登录
     * @param channel
     * @return
     */
    public static boolean hasLogin(Channel channel) {
        return channel.hasAttr(Attributes.SESSION);
    }

    /**
     * 获取连接中的会话
     * @param channel
     * @return
     */
    public static Session getSession(Channel channel) {
        return channel.attr(Attributes.SESSION).get();
    }

    /**
     * 获取用户对应的连接通道
     * @param userId
     * @return
     */
    public static Channel getChannel(String userId) {
        return userIdChannelMap.get(userId);
    }
}
